
package com.zzw.hotspot;


import com.sun.tools.attach.VirtualMachine;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {

 /*   static {
        // hack to pick up tools.jar
        prepareToolsJAR();
    }*/

    public static void main(String[] args) throws Exception {
        VirtualMachine vm = VirtualMachine.attach("6384");
        vm.loadAgent(DumpClassURLByAttach.getPathFromClass(Main.class));
        vm.detach();
    }

    private static void prepareToolsJAR() {
        try {
            //String path = "C:/Program Files/Java/jdk1.8.0_161/lib/tools.jar";

            String path = System.getenv("JAVA_HOME") + File.separator + "lib" + File.separator + "tools.jar";
            URL toolsURL = new File(path).toURI().toURL();

            URLClassLoader loader = (URLClassLoader) Main.class.getClassLoader();
            Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            addURL.setAccessible(true);
            Object invoke = addURL.invoke(loader, toolsURL);
            System.out.println(invoke);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class MyClassLoader extends URLClassLoader {

        public MyClassLoader(URL[] urls) {
            super(urls);
        }

        public MyClassLoader(URL[] urls, ClassLoader parent) {
            super(urls, parent);
        }

        public void addJar(URL url) {
            this.addURL(url);
        }

    }

}
